//index.js
import {
    Index
} from 'index-model.js'
var index = new Index();
import regeneratorRuntime from '../../utils/runtime.js'
//获取应用实例
const app = getApp()

Page({
    data: {
        activity: null,
        inviteCode: '',
        nowSwiper: 0,
        clickBtn: true,
        showReceive: false,
        coupon: "",
        isVip: 0,
        vipModelShow: false,
        addCartShow: false, //是否显示加入购物车
        goodsHide: false, //是否展示商品列表
        cartParams: {
            ctrnum: 1,
            stockNum: 0,
            goodsSize: null
        }, //加入购物车的参数
        isShowPopup: false, //是否显示弹窗
        hotGoods: null,
        hotType: 'today',
        hotTime: '',
        scrollToItemIdx: '0', //底部滚动下标

        videoPlay: true, //默认播放视频
        list: [],
        videoIndex: 0,
        nowVideo: null,
        page: 1,
        size: 10,
        hasMore: true,
        clickNextVideo: true, //下一个防抖
        needShow: false
    },
    onLoad(options) {
        app.aldstat.sendEvent('进入首页');

        wx.showLoading({
            title: '加载中...',
        })
        let sessionId = wx.getStorageSync('sessionId')
        console.log("options----", index.nowV, options);
        // 通过会员直接分享小程序进来
        if (options && options.invitePhone) {
            console.log('通过会员邀请人手机号', options.invitePhone)
            wx.setStorageSync("invitePhone", options.invitePhone);
            this.setData({
                invitePhone: options.invitePhone
            })
        }
        // 通过代购直接分享小程序进来
        if (options && options.inviteDaigoCode) {
            let params = {
                inviteCode: options.inviteDaigoCode
            }
            // 代购推广使用
            wx.setStorageSync('inviteCode', options.inviteDaigoCode)
            console.log('通过代购直接分享小程序进来inviteCode', wx.getStorageSync('inviteCode'))
            if (sessionId !== "") {
                // 绑定邀请码
                index.bindInviteCodeByMiniProgram(params, res => {
                    console.log('首页通过代购直接分享小程序进来绑定邀请码', res)
                    if (res.status) {
                        console.log('首页绑定邀请码成功')
                    }
                })
            }
        }
        //如果扫码进入，代购二维码携带邀请码
        if (options && options.scene) {
            var scene = decodeURIComponent(options.scene);
            if (scene != 'undefined' && scene != null) {
                var sceneList = scene.split(',');
                console.log('扫码进入，二维码邀请人信息', sceneList)
                let inviteCode = sceneList[0];
                this.setData({
                    inviteCode
                })
                wx.setStorageSync('inviteCode', inviteCode);
                let params = {
                    inviteCode
                }
                if (sessionId !== "") {
                    // 绑定邀请码
                    index.bindInviteCodeByMiniProgram(params, res => {
                        console.log('首页扫码进入通过进来绑定邀请码', res)
                        if (res.status) {
                            console.log('绑定邀请码成功')
                        }
                    })
                }
            }
        }
        // 新人红包显示次数
        if (wx.getStorageSync('showTimes') == '1') {
            this.setData({
                storeNo: wx.getStorageSync('storeNo')
            })
        } else {
            this.setData({
                storeNo: wx.getStorageSync('storeNo'),
                showReceive: true
            })
            wx.setStorageSync('showTimes', '1')
        }
        // 爆款
        this.hotChange()

    },
    onShow() {
        let userStatus = wx.getStorageSync('userStatus')
        let vipModelShow = wx.getStorageSync('vipModelShow')
        let sessionId = wx.getStorageSync("sessionId");
        this.setData({
            isVip: userStatus
        })
        this.isOnlineForMiniApp(()=>{
            this.request('onload')        
        })
        // 购买会员之后返回首页提示100优惠券弹窗
        if (userStatus == 1 && vipModelShow == 'show') {
            this.setData({
                vipModelShow: true
            })
            wx.removeStorageSync('vipModelShow')
        }
        if (sessionId !== "") {
            this.getCart()
        }
        this.hotChange()
        // 获取用户上线代购邀请码
        if (sessionId !== '') {
            this.getInviteDaigoCode()
        }
    },
    request(type, cb) {
        let {
            storeNo,
            needShow
        } = this.data
        let params = {
            storeNo
        }
        let timer = null
        index.activityIndex(params, res => {
            if (type == 'onload') {
                wx.hideLoading()
            } else {
                wx.stopPullDownRefresh()
            }
            console.log('index', res)
            if (res.status) {
                if (res.data.ocupon) {
                    res.data.ocupon.startTime = index.formate(res.data.ocupon.startTime, 'yyyy-MM-dd')
                    res.data.ocupon.end_time = index.formate(res.data.ocupon.end_time, 'yyyy-MM-dd')
                }
                res.data.sellList.forEach(val => {
                    val.brandTag = val.brandTag ? val.brandTag.split(',') : []
                })
                res.data.exhibitionList.forEach(val => {
                    val.brandTag = val.brandTag ? val.brandTag.split(',') : []
                })
                if (needShow){
                    this.setData({
                        activity: res.data,
                        coupon: res.data.ocupon
                    })
                }else{
                    res.data.sellList = [res.data.sellList[0]]
                    res.data.exhibitionList = []
                    this.setData({
                        activity: res.data,
                        coupon: res.data.ocupon
                    })
                }
                clearInterval(timer)
                this.countDown()
                timer = setInterval(() => {
                    this.countDown()
                }, 1000)
                cb && cb()
            } else {
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
            }
        })

    },
    onReady: function(res) {
        this.videoContext = wx.createVideoContext('myVideo')

    },
    // 顶部三个按钮切换
    scrollToItem(e) {
        let type = index.getDataSet(e, 'type')
        this.setData({
            scrollToItemIdx: type
        })
        let query = wx.createSelectorQuery()
        if (type > 0) {
            let item = type === '1' ? '#sellList' : '#exhibitionList'
            query.select(item).boundingClientRect()
            query.selectViewport().scrollOffset()
            query.exec(function(res) {
                console.log(res)
                if (res[0]) {
                    wx.pageScrollTo({
                        scrollTop: res[0].top + res[1].scrollTop - 50,
                        duration: 0
                    })
                } else {
                    let query = wx.createSelectorQuery()
                    query.select('.weui-loadmore_line').boundingClientRect()
                    query.selectViewport().scrollOffset()
                    query.exec(function(res) {
                        console.log('res2', res)
                        wx.pageScrollTo({
                            scrollTop: res[0].top + res[1].scrollTop - 50,
                            duration: 0
                        })
                    })
                }
            })
        } else {
            wx.pageScrollTo({
                scrollTop: 0,
                duration: 0
            })
        }
    },
    onPageScroll(e) {
        // console.log(e)
        // let { activity, scrollToItemIdx} = this.data
        // let that = this
        // let query1 = wx.createSelectorQuery()
        // query1.select('#sellList').boundingClientRect()
        // query1.selectViewport().scrollOffset()
        // query1.exec(function (res) {
        //     // 使页面滚动到底部
        //     console.log(res[0].top,e.scrollTop)
        //     if (e.scrollTop < 200){
        //         that.setData({
        //             scrollToItemIdx: '0'
        //         })
        //     }
        //     if (res[0].top < 50 && res[0].top > -activity.sellList.length * 400){
        //         if (scrollToItemIdx !== '1') {
        //             that.setData({
        //                 scrollToItemIdx: '1'
        //             })
        //         }
        //     }
        // })
        // let query2 = wx.createSelectorQuery()
        // query2.select('#exhibitionList').boundingClientRect()
        // query2.selectViewport().scrollOffset()
        // query2.exec(function (res) {
        //     // 使页面滚动到底部
        //     // console.log(res[0].top)
        //     if(res[0]){
        //         if (res[0].top < 100 && res[0].top > -activity.exhibitionList.length * 400) {
        //             if (scrollToItemIdx !== '2') {
        //                 that.setData({
        //                     scrollToItemIdx: '2'
        //                 })
        //             }
        //         }
        //     }
        // })
    },
    onReachBottom() {
        // this.setData({
        //     scrollToItemIdx: '2'
        // })
    },
    onPullDownRefresh() {
        this.isOnlineForMiniApp(() => {
            this.request('', () => {
                this.setData({
                    nowSwiper: 0
                })
            })
        })
        this.hotChange()
        this.setData({
            hotType: 'today'
        })
    },
    //点击查看大图
    preview(e) {
        console.log(e)
        let val = e.currentTarget.dataset
        let {
            activity
        } = this.data
        let index = val.index
        let curImg = val.img
        let type = val.type
        let images = activity[type][index]['imageList']
        let imgList = []
        images.forEach(val => {
            imgList.push(val.mediaUrl)
        })
        console.log(activity[type][index])
        wx.previewImage({
            current: curImg,
            urls: imgList
        })
    },
    jump(e) {
        let sessionId = wx.getStorageSync("sessionId");
        if (sessionId != "") {
            let id = e.currentTarget.dataset.id
            wx.navigateTo({
                url: '/pages/home/home?id=' + id,
            })
        } else {
            // wx.setStorageSync("inviteCode", this.data.inviteCode);
            wx.navigateTo({
                url: '/pages/getUserInfo/getUserInfo'
            })
        }
    },
    // banner跳转
    isJump(e) {
        let dataset = e.currentTarget.dataset
        let action = dataset.action
        let url = dataset.link
        if (action == 1) {
            let sessionId = wx.getStorageSync("sessionId");
            if (sessionId !== "") {
                let id = e.currentTarget.dataset.id
                if (wx.getStorageSync('phone') === '') {
                    wx.navigateTo({
                        url: '/pages/signin/signin?path=/pages/role/ordinary/ordinary',
                    })
                } else if (this.data.isVip === 1 && url.indexOf('ordinary') >= 0) {
                    wx.navigateTo({
                        url: '/pages/role/member/member',
                    })
                } else if (this.data.isVip > 1){
                    wx.showToast({
                        title: '您是代购了，不能进入会员中心！',
                        icon: 'none'
                    })
                } else {
                    wx.navigateTo({
                        url
                    })
                }
            } else {
                wx.navigateTo({
                    url: '/pages/getUserInfo/getUserInfo'
                })
            }

        }
    },
    // 获取购物车数量
    getCart() {
        let that = this;
        let {
            storeNo
        } = this.data;
        let parames = {
            "storeNo": '' + storeNo
        }
        index.getCart(parames, res => {
            if (res.status) {
                let total = 0;
                res.data.forEach((value, index) => {
                    value.list.forEach((val, index) => {
                        total += parseInt(val.goodsNum);
                    });
                })
                //设置购物车右上角红色点
                if (total == 0) {
                    wx.hideTabBarRedDot({
                        index: 1
                    })
                } else {
                    wx.showTabBarRedDot({
                        index: 1
                    })
                    wx.setTabBarBadge({
                        index: 1,
                        text: '' + total,
                    })
                }


            }
        })
    },
    // 分享
    onShareAppMessage: function() {
        app.aldstat.sendEvent('首页-分享');

        wx.showShareMenu({
            withShareTicket: true
        });

        let phone = wx.getStorageSync('phone'),
            invitePhone = wx.getStorageSync('invitePhone'),
            inviteDaigoCode = wx.getStorageSync('inviteDaigoCode'),
            ownInviteCode = wx.getStorageSync('ownInviteCode'),
            userStatus = wx.getStorageSync('userStatus'),
        // 如果自己是代购以上身份就用自己邀请码，否则是上游邀请码
            nowInviteCode = userStatus > 1 ? ownInviteCode : inviteDaigoCode,
            path = '';
        if (!nowInviteCode) {
            console.log('用户没有登录-分享的')
            nowInviteCode = wx.getStorageSync('inviteCode');
        }
        console.log("分享的", phone, inviteDaigoCode, ownInviteCode)
        if ((!userStatus || userStatus === 0) && nowInviteCode){
            path = `inviteDaigoCode=${nowInviteCode}`
        } else if (userStatus === 1){
            path = `invitePhone=${phone}`
        } else if (userStatus > 1){
            path = `inviteDaigoCode=${nowInviteCode}`
        }
        return {
            title: "一线品牌一折起", //storeInfo.brandName,
            path: `/pages/index/index?${path}`,
            imageUrl: "https://goods.dingdian.xin/Fp3ptFYZ54XLi2L2OuAMjP_D45hJ?imageMogr2/thumbnail/400000@",
            success: res => {
                if (res.shareTickets) {
                    console.log(res.shareTickets);
                    wx.getShareInfo({
                        shareTicket: res.shareTickets[0],
                        success: d => {
                            console.log(d);
                        }
                    })
                }
            }
        }
    },
    // 立即领取
    receive() {
        let sessionId = wx.getStorageSync('sessionId');
        if (sessionId == "") {
            wx.navigateTo({
                url: '/pages/getUserInfo/getUserInfo',
            })
            return
        }
        //如果已经领取
        console.log(this.data.isReceive);
        if (this.data.isReceive) {
            wx.showToast({
                title: "您已领取过此优惠券",
                icon: 'none'
            })
            return
        }

        this.setData({
            clickBtn: false
        })
        wx.showLoading({
            title: '加载中...',
        })
        let params = {
            "couponIds": '' + this.data.coupon.id
        }
        index.receive(params, res => {
            let data = res.data;
            if (res.status) {

                wx.hideLoading();

                if (data.length == 0) {
                    wx.showToast({
                        title: '该优惠券已拥有',
                    })
                    this.setData({
                        clickBtn: true,
                        showReceive: false,
                        isReceive: true
                    })
                    return
                }
                wx.showToast({
                    title: '优惠券领取成功',
                })
                this.setData({
                    showReceive: false,
                    clickBtn: true,
                    isReceive: true
                })
            } else {
                wx.showToast({
                    title: res.message,
                    icon: 'none'
                })
            }
        })
    },
    closeReceive() {
        this.setData({
            showReceive: false
        })
    },
    // 爆款切换
    hotChange(e) {
        let now;
        let {
            hotType
        } = this.data
        if (e) {
            now = index.getDataSet(e, 'type')
        } else {
            now = hotType
        }
        this.setData({
            hotType: now
        })
        let time
        let date = new Date()
        switch (now) {
            case 'today':
                app.aldstat.sendEvent('爆款切换', {
                    '日期': '今天'
                });
                time = index.formate(date.getTime(), 'yyyy/MM/dd');
                break
            case 'yesterday':
                app.aldstat.sendEvent('爆款切换', {
                    '日期': '昨天'
                });

                time = index.formate(new Date(date.setDate(date.getDate() - 1)).getTime(), 'yyyy/MM/dd');
                break
            case 'tomorrow':
                app.aldstat.sendEvent('爆款切换', {
                    '日期': '明天'
                });
                time = index.formate(new Date(date.setDate(date.getDate() + 1)).getTime(), 'yyyy/MM/dd');
                break

        }
        console.log(time)
        let params = {
            "startTime": new Date(time + ' 00:00:00').getTime(),
            "endTime": new Date(time + ' 23:59:59').getTime()
        }

        index.getHotGoods(params, res => {
            if (res.status) {
                res.data.forEach(val => {
                    val.nowTime = new Date().getTime()
                })
                this.setData({
                    hotGoods: res.data
                })
                if (res.data.length > 0) {
                    this.setData({
                        hotTime: index.formate(res.data[0].presaleTime, 'hh:mm')
                    })
                }
            }
        })
    },
    //加入购物车
    addCartShow(e) {
        app.aldstat.sendEvent('爆品-马上抢');
        let sessionId = wx.getStorageSync("sessionId");
        if (sessionId == "") {
            wx.navigateTo({
                url: '/pages/getUserInfo/getUserInfo'
            })
            return
        }
        let id = index.getDataSet(e, 'id');
        let params = {
            "goodsId": "" + id
        }
        wx.showLoading({
            title: '加载中...',
        })

        index.getGoodsById(params, res => {
            wx.hideLoading()
            if (res.status) {
                //选中尺寸
                let goodsSize = this.canSizeVaild(res.data)
                this.setData({
                    newGoodsList: res.data,
                    addCartShow: true,
                    "cartParams.ctrnum": 1,
                    "cartParams.goodsSize": goodsSize
                })
            } else {
                wx.showToast({
                    title: res.message,
                    icon: 'none'
                })
            }
        })

    },
    //隐藏加入购物车弹框
    addCartHide(e) {
        this.setData({
            addCartShow: false
        })
    },
    //点击商品颜色
    onColorOption(e) {
        let goodsId = index.getDataSet(e, "id");
        let storeNo = this.data.storeNo;
        let that = this;
        let params = {
            "storeNo": "" + storeNo,
            "goodsId": "" + goodsId
        }
        index.getGoodsById(params, res => {
            let status = res.status;
            let data = res.data;
            if (status) {
                let goodsSize = this.canSizeVaild(data)
                that.setData({
                    "newGoodsList": data,
                    "cartParams.ctrnum": 1,
                    "cartParams.goodsSize": goodsSize
                })
            }
        });
    },
    //选择商品尺寸
    onSizeOption(e) {
        let goodsSize = index.getDataSet(e, "key");
        let {
            cartParams
        } = this.data;
        let ctrnum = cartParams.ctrnum;
        let stockNum = goodsSize.stockNum;
        let oldGoodsSize = cartParams.goodsSize;
        if (stockNum && ctrnum > stockNum) {
            ctrnum = stockNum;
        }
        if (oldGoodsSize && goodsSize.id == oldGoodsSize.id) {
            goodsSize = null;
        }

        if (goodsSize != "") {
            this.setData({
                "cartParams.goodsSize": goodsSize,
                "cartParams.ctrnum": ctrnum
            })
        }
    },
    //数量减
    onNumMinus(e) {
        let {
            cartParams
        } = this.data;
        if (!cartParams.goodsSize || cartParams.goodsSize == "") {
            wx.showToast({
                title: '请选择商品尺寸',
                icon: 'none'
            })
            return;
        }
        let ctrnum = cartParams.ctrnum;
        if (cartParams.ctrnum > 1) {
            ctrnum--;
            this.setData({
                "cartParams.ctrnum": ctrnum
            })
        }
    },
    //数量加
    onNumAdd(e) {
        let {
            cartParams
        } = this.data;
        if (!cartParams.goodsSize || cartParams.goodsSize == "") {
            wx.showToast({
                title: '请选择商品尺寸',
                icon: 'none'
            })
            return;
        }
        let ctrnum = cartParams.ctrnum;
        if (ctrnum < cartParams.goodsSize.stockNum) {
            ctrnum++;
            this.setData({
                "cartParams.ctrnum": ctrnum
            })
        }
    },
    //加入购物车
    addCart(e) {
        app.aldstat.sendEvent('首页-爆品-加入购物车');
        let {
            newGoodsList,
            storeNo,
            cartParams,
            isVip
        } = this.data;
        let that = this;
        // 判断尺码是否为空
        if (cartParams.goodsSize == null) {
            wx.showToast({
                title: '请选择尺寸',
                icon: 'none'
            })
            return;
        }

        //判断数值
        if (cartParams.ctrnum <= 0) {
            wx.showToast({
                title: '请添加数量',
                icon: 'none'
            })
            return;
        }
        let goodsId = newGoodsList.goodsId;
        let goodsName = newGoodsList.goodsName
        let goodsPrice = isVip === 0 ? newGoodsList.discountPrice :
            ((newGoodsList.memberPrice && newGoodsList.memberPrice != '') ? newGoodsList.memberPrice : newGoodsList.discountPrice)
        let goodsColor = newGoodsList.goodsColor
        let goodsPic = newGoodsList.goodsPic
        let originalPrice = newGoodsList.goodsPrice
        let discountPrice = newGoodsList.discountPrice

        let params = {
            "storeNo": "" + storeNo,
            "goodsId": "" + goodsId,
            "goodsName": "" + goodsName,
            "goodsNum": "" + cartParams.ctrnum,
            "goodsPrice": "" + goodsPrice,
            "discountPrice": "" + discountPrice,
            "goodsColor": "" + goodsColor,
            "specsName": "" + cartParams.goodsSize.specsName,
            "goodsPic": "" + goodsPic,
            "originalPrice": "" + originalPrice,
            "activityId": "" + newGoodsList.activityId
        }
        if (isVip > 0) {
            params.memberPrice = '' + newGoodsList.memberPrice
        }
        console.log(params);
        if (newGoodsList.soldout == 0) {
            index.getAddCart(params, res => {
                let status = res.status;
                let data = res.data;
                if (status) {
                    wx.showToast({
                        title: '加入购物车成功',
                        icon: 'none'
                    })
                    // this.getCart();
                    setTimeout(function() {
                        that.addCartHide();
                    }, 400);
                }
            })
        }

    },
    // 跳转商品详情
    jumpProductDetail(e) {
        let sessionId = wx.getStorageSync("sessionId");
        if (sessionId == "") {
            wx.navigateTo({
                url: '/pages/getUserInfo/getUserInfo'
            })
            return
        }
        let id = index.getDataSet(e, 'id');
        wx.navigateTo({
            url: '/pages/product/product?id=' + id,
        })
    },
    jumpLogin(e, cb) {
        let sessionId = wx.getStorageSync("sessionId");
        if (sessionId === "") {
            wx.navigateTo({
                url: '/pages/getUserInfo/getUserInfo'
            })
        } else {
            cb && cb()
        }
    },
    // 跳转购买会员页
    jumpOrdinary() {
        let phone = wx.getStorageSync("phone");
        if (phone === "") {
            wx.navigateTo({
                url: '/pages/signin/signin?path=/pages/role/ordinary/ordinary',
            })
        } else {
            wx.navigateTo({
                url: '/pages/role/ordinary/ordinary',
            })
        }
    },
    // 定时器
    countDown() {
        let {
            activity
        } = this.data
        let date = new Date();
        let aDay = 24 * 60 * 60 * 1000; //一天时间

        activity.sellList.forEach((val) => {
            let endTime = val.endTime;
            var diffDay = (endTime - date) / aDay;
            if (diffDay >= 1) {
                val.diffDay = parseInt(diffDay)
            } else {
                val.diffDay = 0
            }
            val.clock = index.countdown(val.endTime)
        })
        activity.exhibitionList.forEach((val) => {
            let startTime = val.startTime;
            var diffDay = (startTime - date) / aDay;
            if (diffDay >= 1) {
                val.diffDay = parseInt(diffDay)
            } else {
                val.diffDay = 0
            }
            val.clock = index.countdown(startTime)
        })
        this.setData({
            activity
        })
    },
    // 隐藏vip弹窗
    hideVipModel() {
        this.setData({
            vipModelShow: false
        })
    },
    // 获取绑定代购邀请码
    getInviteDaigoCode() {
        index.getUserInfo({}, res => {
            if (res.status) {
                let data = res.data
                console.log('代购邀请码', data)
                wx.setStorageSync('inviteDaigoCode', data ? data.inviteCode : '')
                wx.setStorageSync('userStatus', data ? data.userStatus : 0)
                wx.setStorageSync('ownInviteCode', data ? data.ownInviteCode : '')
            }
        })
    },
    // 爆款查看大图
    showImg(e) {
        //查看大图
        let imgurl = index.getDataSet(e, "img");
        let imgurls = [];
        imgurls.push(imgurl);
        if (imgurls && imgurls.length > 0) {
            wx.previewImage({
                current: imgurl,
                urls: imgurls
            })
        }
    },
    // 检测当前尺寸是否可用
    canSizeVaild(data) {
        let goodsSize;
        let thatSizes = data.goodsSize ? data.goodsSize : data.goodsStock;

        if (thatSizes[0].stockNum > 0) {
            goodsSize = thatSizes[0];
        } else {
            for (let i = 0; i < thatSizes.length; i++) {
                if (thatSizes[i].stockNum > 0) {
                    goodsSize = thatSizes[i];
                    break;
                } else {
                    goodsSize = ""
                }
            }

        }
        return goodsSize;
    },
    jumpVideo(e) {
        this.jumpLogin(e, () => {
            // wx.navigateTo({
            //     url: '/pages/video/video',
            // })
            this.setData({
                // list: [],
                // page: 1,
                // videoIndex: 0,
                clickNextVideo: true
            })
            console.log(this.data.page, this.data.videoIndex)
            this.videoContext.requestFullScreen({
                direction: 0
            })
            if (this.data.list.length === 0) {
                this.getList(() => {
                    this.videoContext.requestFullScreen({
                        direction: 0
                    })
                    this.videoContext.play();
                });
            } else {
                this.videoContext.requestFullScreen({
                    direction: 0
                })
                this.videoContext.play();
                this.setData({
                    videoPlay: true
                });
            }
        })
    },
    nextVideo() {
        if (this.data.clickNextVideo) {
            this.setData({
                clickNextVideo: false
            })

            this.initData(() => {
                this.setData({
                    clickNextVideo: true
                })
            })
        }
    },
    //视频暂停播放
    handVideo() {
        let {
            videoPlay
        } = this.data;
        if (videoPlay) {
            this.videoContext.pause();
        } else {
            this.videoContext.play();
        }

    },
    //视频播放执行
    VideoPlay() {
        let {
            videoPlay
        } = this.data;
        this.setData({
            videoPlay: true
        })
    },
    //视频暂停执行
    VideoPause() {
        let {
            videoPlay
        } = this.data;
        this.setData({
            videoPlay: false
        })
    },
    //记录点击事件
    videoClickIncr(relation, actionType) {
        let params = {
            "relation": relation ? relation : "",
            "actionType": actionType ? actionType : "",
        }
        index.videoClickIncr(params, res => {
            if (res.status) {
                console.log("记录成功");
            }
        })
    },
    getList(cb) {

        let { page, size, list, hasMore , videoIndex } = this.data;
        let params = { page, size }
        if (hasMore) {
            index.goodsVideoList(params, res => {
                wx.hideLoading();
                if (res.status) {
                    let data = res.data;
                    let total = res.total;

                    if (page > Math.ceil(total / size)) {
                        console.log("结束了");
                        this.setData({
                            videoIndex: 0,
                            hasMore: false,
                            clickNextVideo: true
                        })
                    
                        this.initData();
                    } else {
                        data = [...list, ...data]
                        this.setData({
                            list: data,
                            clickNextVideo: true
                        })
                        cb && cb();
                        this.initData();
                    }
                } else {
                    wx.showToast({
                        title: res.message,
                        icon: 'none'
                    })
                }
            })
        } else {
            this.setData({
                videoIndex: 0
            })
        }
    },
    initData(cb) {
        let {
            list,
            videoIndex,
            page,
            hasMore
        } = this.data;


        if ((videoIndex >= list.length) && hasMore) {

            page = page + 1
            this.setData({
                page
            })
            this.getList(() => {});
            return;
        }

        if (list.length > 0 && videoIndex <= list.length) {
            let nowVideo = list[videoIndex]
            console.log("nowVideo", nowVideo)

            //记录点击
            this.videoClickIncr("" + nowVideo.relation, "view");
            videoIndex++;

            this.setData({
                nowVideo,
                videoIndex,
                videoPlay: true,
            })
            cb && cb()

        }
    },
    //查看详情
    onProductDetail() {
        this.outFullScreen();
        var {
            nowVideo
        } = this.data;
        //记录点击
        this.videoClickIncr("" + nowVideo.goodsId, "detail");
        wx.navigateTo({
            url: '/pages/product/product?id=' + nowVideo.goodsId,
        })
    },
    // 视频退出全屏
    outFullScreen() {
        this.videoContext.pause()
        this.videoContext.exitFullScreen()
    },
    // 监听视频全屏
    bindfullscreenchange(e) {
        console.log(e.detail)
        if (!e.detail.fullScreen) {
            this.videoContext.pause()
        }
    },
    goActivity() {
        let {
            nowVideo
        } = this.data;

        this.outFullScreen();
        wx.navigateTo({
            url: "/pages/home/home?id=" + nowVideo.activityId
        })
    },
    isOnlineForMiniApp(cb){
        index.isOnlineForMiniApp({},res=>{
            if(res.data){
                wx.setStorageSync('needShow', res.data.version)
                this.setData({
                    needShow: res.data.version == index.nowV ? false : true
                })
                cb && cb()
            }
        })
    }
})